<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="roleName" label="角色名称">
          <el-input
            v-noSpace
            v-model="queryParams.roleName"
            placeholder="请输入角色名称"
            clearable
            class="!w-[192px]"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button v-hasPerm="'sys:role:edit'" type="warning" @click="handleOpenDialog()">
            新增
          </el-button>
          <!-- <el-button @click="handleDelete()">删除</el-button> -->
          <el-button @click="handleResetQuery()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="roleList"
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="序号" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="角色名称" prop="roleName" align="center" />
        <el-table-column label="角色描述" prop="description" align="center" />
        <el-table-column label="角色权限" prop="sysRoleModuleList" align="center">
          <template #default="scope">
            <div v-if="scope.row.roleName === 'admin'">
              <el-tag type="info">全部权限</el-tag>
            </div>
            <div v-else class="gap-2">
              <el-tag
                v-for="item in scope.row.sysRoleModuleList.slice(0, 1)"
                :key="item.moduleId"
                size="small"
              >
                {{ item.moduleName }}
              </el-tag>
              <el-tooltip
                v-if="scope.row.sysRoleModuleList.length > 1"
                effect="dark"
                placement="top"
              >
                <el-tag type="info">+{{ scope.row.sysRoleModuleList.length - 1 }} 更多</el-tag>
                <template #content>
                  {{ scope.row.sysRoleModuleList.map((item: any) => item.moduleName).join(",") }}
                </template>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" align="center" />
        <el-table-column label="创建人" prop="createName" align="center" />

        <el-table-column fixed="right" label="操作" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.roleName === 'admin'" type="info">不可操作</el-tag>
            <div v-else>
              <el-button
                v-hasPerm="'sys:role:edit'"
                type="primary"
                size="small"
                link
                @click="handleOpenDialog(scope.row.id, scope.row)"
              >
                编辑
              </el-button>
              <el-button
                v-hasPerm="'sys:role:del'"
                type="danger"
                size="small"
                link
                @click="handleDelete(scope.row.id)"
                v-if="scope.row.allowDel == 1"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 角色表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      :close-on-click-modal="false"
      @close="handleCloseDialog"
    >
      <el-form ref="roleFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-noSpace v-model="formData.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色权限" label-width="100px" prop="sysRoleModuleList">
          <!-- <el-select
            v-model="formData.sysRoleModuleList"
            multiple
            placeholder="请选择角色权限"
            style="width: 250px"
            @change="handleChangeSelect"
          >
            <el-option
              v-for="item in roleModelOptions"
              :key="item.moduleId"
              :label="item.label"
              :value="item.moduleId"
            />
          </el-select> -->
          <!-- <el-tag
                v-for="item in formData?.sysRoleModuleList.slice(0, 1)"
                :key="item.moduleId"
                size="small"
              >
                {{ item.moduleName }}
              </el-tag> -->
          <el-select
            v-model="sysRoleModuleName"
            @visible-change="selectChange"
            collapse-tags
            multiple
            placeholder="请选择"
          >
            <!-- <template #prefix>
              <el-tag v-for="item in formData.sysRoleModuleList" :key="item.moduleId" size="small">
                {{ item.moduleName }}
              </el-tag>
            </template> -->
            <el-option hidden />
            <el-tree
              ref="cascaderRef"
              :data="roleModelOptions"
              show-checkbox
              node-key="id"
              :check-strictly="true"
              :props="cascaderProps"
              style="width: 100%; height: 300px; overflow-y: auto"
              @check="handleChangeSelect"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="角色描述">
          <el-input
            v-noSpace
            v-model="formData.description"
            type="textarea"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <!-- <el-form-item label="创建人" prop="createName">
          <el-input v-noSpace v-model="formData.createName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-input v-noSpace v-model="formData.createTime" placeholder="请输入角色名称" />
        </el-form-item> -->
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button v-debounce="handleSubmit" type="primary">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Role",
  inheritAttrs: false,
});

import RoleAPI, { RolePageVO, RoleForm, RolePageQuery, Module } from "@/api/system/role";
import sysModuleAPI from "@/api/system/sysModule";

const queryFormRef = ref(ElForm);
const roleFormRef = ref(ElForm);
const permTreeRef = ref<InstanceType<typeof ElTree>>();

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

//定义下拉框ref
const cascaderRef = ref();

const queryParams = reactive<RolePageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 配置级联
const cascaderProps = reactive({
  // expandTrigger: "hover" as const,
  label: "moduleName",
  value: "id",
  children: "sysModuleList",
});

// 角色表格数据
const roleList = ref<RolePageVO[]>();
// 菜单权限下拉
const roleModelOptions = ref();

//行数据
let rowOptions = ref<any[] | undefined>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});
// 角色表单
const formData = reactive<RoleForm>({
  sysRoleModuleList: [],
});
const sysRoleModuleName = ref([]);

const rules = reactive({
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  sysRoleModuleList: [{ required: true, message: "请选择角色权限", trigger: "blur" }],
  description: [{ required: true, message: "请输入角色编码", trigger: "blur" }],
});

// 选中的角色
interface CheckedRole {
  id?: number;
  name?: string;
}

const permKeywords = ref("");

// 查询
function handleQuery() {
  loading.value = true;
  RoleAPI.getPage(queryParams)
    .then((data) => {
      //console.log(data);

      roleList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

// 行复选框选中
async function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}
const selectChange = (val) => {
  if (val) {
    nextTick(() => {
      cascaderRef.value.setCheckedKeys(formData.sysRoleModuleList);
      console.log(cascaderRef.value, "cascaderRef.value");
      console.log(formData.sysRoleModuleList, "formData.sysRoleModuleList");
    });
  } else {
    console.log(formData.sysRoleModuleList);
  }
};
// 打开角色弹窗
async function handleOpenDialog(roleId?: number, row?: RolePageVO) {
  console.log(row?.sysRoleModuleList, "行复选框选中");

  roleModelOptions.value = await sysModuleAPI.getSysModuleList();
  console.log(roleModelOptions, "roleModelOptions");
  rowOptions.value = row?.sysRoleModuleList;

  dialog.visible = true;
  if (roleId) {
    dialog.title = "修改角色";
    //根据roleId获取角色数据
    let list = getAllModuleIds(row?.sysRoleModuleList);
    formData.id = roleId;
    formData.roleName = row?.roleName;
    formData.description = row?.description;
    formData.sysRoleModuleList = list.map((item) => item.moduleId);
    sysRoleModuleName.value = list.map((item) => item.moduleName);
  } else {
    dialog.title = "新增角色";
  }
}
const handleActiveItemChange = (val: any) => {
  console.log(val, "选中");
};

// 提交角色表单
function handleSubmit() {
  let queryParams: any = {
    ...formData,
    sysRoleModuleList: getPermissions(),
  };
  console.log(queryParams, "query提交");

  roleFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const roleId = formData.id;
      //console.log(roleId, "表单id");

      if (roleId) {
        RoleAPI.update(queryParams)
          .then((data) => {
            //console.log(data, "修改");
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .catch((err) => {
            //console.log(err);
            // ElMessage.error(`${err}`);
            // handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        RoleAPI.add(queryParams)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .catch((err) => {
            //console.log(err);
            // ElMessage.error(`${err}`);
            // handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;

  roleFormRef.value?.resetFields();
  roleFormRef.value?.clearValidate();

  formData.id = undefined;
  formData.roleName = "";
  formData.description = "";
  formData.sysRoleModuleList = [];
  sysRoleModuleName.value = [];
}

// 删除角色
function handleDelete(roleId: number) {
  // const roleIds = [roleId || ids.value].join(",");
  // if (!roleIds) {
  //   ElMessage.warning("请勾选删除项");
  //   return;
  // }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      RoleAPI.deleteByIds(roleId)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .catch((err) => {
          //console.log(err);

          // ElMessage.error(`${err}`);

          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

//权限下拉
const handleChangeSelect = (data: any, checkedStatus: any) => {
  if (checkedStatus.checkedKeys.includes(data.id)) {
    selectParent(data);
  }
  let list = cascaderRef.value.getCheckedNodes();
  sysRoleModuleName.value = list.map((item) => item.moduleName);
  formData.sysRoleModuleList = list.map((item) => item.moduleId);
};
const selectParent = (node: any) => {
  const nodeObj = cascaderRef.value.getNode(node);

  if (nodeObj.parent && nodeObj.parent.level > 0) {
    cascaderRef.value.setChecked(nodeObj.parent.data.id, true, false);
    selectParent(nodeObj.parent.data);
  }
};

//提交时获取所有权限
const getPermissions = () => {
  //选中节点
  let actNodes = cascaderRef.value.getCheckedNodes();
  //选中节点id，其实为moduleId
  let actIDArr: number[] = [];
  actNodes = actNodes.forEach((item: any) => actIDArr.push(item.id));

  //将行数据存储到map中，为了根据行数据id找到对应的权限id
  const permissionsMap =
    new Map(rowOptions.value?.map((item: any) => [item.moduleId, item.id])) || new Map();
  //处理的数据
  const formattedPermissions = [];
  // 遍历选中节点id，根据id在行数据中查找匹配项，如果找到则将该行的id赋值到处理的数据中，否则为undefined
  for (const moduleId of actIDArr) {
    let module = findModuleById(roleModelOptions.value, moduleId);
    if (module) {
      const permissionId = permissionsMap.get(moduleId) || undefined;
      const permission = {
        id: permissionId || undefined, // 如果在rowData中找到匹配项，则使用其id，否则为undefined
        moduleId: moduleId,
        moduleName: module.moduleName,
      };

      formattedPermissions.push(permission);
    } else {
      console.warn(`Module with ID ${moduleId} not found in resData.`);
    }
  }
  return formattedPermissions;
};

// function formatFormDataToPermissions(resData: any, actId: any, rowData?: any) {
//   const permissionsMap =
//     new Map(rowData?.map((item: any) => [item.moduleId, item.id])) || new Map();
//   const formattedPermissions = [];

//   for (const id of actId) {
//     let module = findModuleById(resData, id);

//     if (module) {
//       const permissionId = permissionsMap.get(id) || undefined;
//       const permission = {
//         id: permissionId || undefined, // 如果在rowData中找到匹配项，则使用其id，否则为undefined
//         moduleId: id,
//         moduleName: module.moduleName,
//       };

//       formattedPermissions.push(permission);
//     } else {
//       console.warn(`Module with ID ${id} not found in resData.`);
//     }
//   }
//   if (rowData && rowData?.length === 1) {
//     // 如果rowData中只有一项，将其id赋值到处理的数据的第一项id
//     const firstPermission = formattedPermissions[0];
//     if (firstPermission) {
//       firstPermission.id = rowData[0].id;
//     }
//   }
//   return formattedPermissions;
// }

function findModuleById(modules: any, id: any) {
  for (const module of modules) {
    if (module.id === id) {
      return module;
    }
    const submodule: any = findModuleById(module.sysModuleList, id);
    if (submodule) {
      return submodule;
    }
  }
  return null;
}

/**
 * 获取所有模块ID的函数
 *
 * @param data 包含模块信息的数组
 * @returns 包含所有模块ID的数组
 */
function getAllModuleIds(data: any) {
  const moduleIds = <any>[];
  console.log(data, "数据");

  function recursiveCollect(item: any) {
    if (item.moduleId) {
      moduleIds.push(item);
    }
    if (item.sysModuleList && item.sysModuleList.length > 0) {
      item.sysModuleList.forEach((subItem: any) => {
        recursiveCollect(subItem);
      });
    }
  }

  data.forEach((item: any) => {
    recursiveCollect(item);
  });

  return moduleIds;
}

// 权限筛选
onMounted(() => {
  handleQuery();
});
</script>
<style scoped></style>
